//
//  Func_iOS.m
//  Demo
//
//  Created by migame on 15/12/14.
//
//

#include "HttpNode.h"
#include "DownLoadCenter.h"
//#import "XMLReader.h"


using namespace cocos2d::network;



#pragma -mark
#pragma -mark
bool HttpNode::init()
{
    if ( Node::init()==false ) return false;
    m_singleDownEndFunc = nullptr;
    m_isBusying = false;
    m_isSingle = false;
    m_myURL = "";
    m_taskId = -1;
    m_inTaskIdx = -1;
    downImgInfo.reset();
    return true;
}



void HttpNode::setIsSingle(bool is)
{
    m_isSingle = true;
}



bool HttpNode::isBusying(){
    return m_isBusying;
};



#pragma -mark
void HttpNode::setSingleDownEndFunc(std::function<void(std::string url)> f){
    m_singleDownEndFunc = f;
}



bool HttpNode::isImgExist(int taskId, int inTaskIdx)
{
    std::string imgFilePath = DownLoadCenter::getNowWebImgFilePath(taskId, inTaskIdx);
    return FileUtils::getInstance()->isFileExist(imgFilePath);
}





#pragma -mark
void HttpNode::downWeb(std::string url, int taskId)
{
    if( m_isBusying ) return;
    m_isBusying = true;
    m_myURL = url;
    m_taskId = taskId;
    // 网络异步连接方法
    HttpRequest* postRequest = new HttpRequest();
    postRequest->setRequestType( HttpRequest::Type::POST );//设置发送类型
    postRequest->setUrl( url.c_str() );//设置网址
    postRequest->setResponseCallback( [=](HttpClient* client, HttpResponse* response){
        onConnectToWebEnd(this, response);
    });
    // 传入参数
    std::string para = "";
    __String *paraStr = __String::create(para);
    postRequest->setRequestData(paraStr->getCString(),paraStr->length());
    // 下载。
    HttpClient* httpClient = HttpClient::getInstance();
    httpClient->setTimeoutForConnect(10); //设置连接超时时间</span> <span style="font-family: Arial, Helvetica, sans-serif;">
    httpClient->setTimeoutForRead(10);//设置发送超时时间
    httpClient->send(postRequest);//设置接收数据类型
    postRequest->release();//释放
}

void HttpNode::onConnectToWebEnd(HttpNode *sender ,HttpResponse *response)
{
    if(!response) {
        log("Log:response =null,plase check it.");
        return;
    }
    //请求失败
    if(!response->isSucceed())
    {
        log("onConnectToWebEnd ERROR:%s",response->getErrorBuffer());
        return;
    }

    int codeIndex = response->getResponseCode();
    const char* tag=response->getHttpRequest()->getTag();

    //请求成功
    std::vector<char>* buffer=response->getResponseData();
    std::string temp(buffer->begin(),buffer->end());
    __String* responseData = __String::create(temp);
    std::string resStr = responseData->getCString();

    // 打印有用消息。
    NSString *resOC = [[NSString alloc] initWithFormat:@"%s", resStr.c_str() ];

    // 标题
    NSString *tOc1 = [resOC componentsSeparatedByString:@" - 69"][0];
    NSString *titOC = [[tOc1 componentsSeparatedByString:@"<title>"] lastObject];
    char titBack[1024*2] = {0};
    if( [titOC length]<1024*2-1 )
        [titOC getCString:titBack];
    char allChar[1024*16] = {0};
    if( [resOC length]<1024*16-1 )
        [resOC getCString:allChar];
//    log("\n\n 标题:[%s]", titBack );
    log(" [%d] web down END  [titOC length]=%ld", m_taskId , [titOC length] );
    if( [titOC length]<110 )
        log("[task:%d] [ url:  %s ] \n[标题:%s] \n\n", m_taskId,  m_myURL.c_str(), titBack );
    return;
//    log("网页的返回内容 : \n%s", allChar);


    // 获取链接数组
    NSArray *cutAry = [resOC componentsSeparatedByString:@"<img src=\""];
//    log(" 站点链接== %s ", m_myURL.c_str() );
    int imgs = 0;
    MyArray *imgUrls = MyArray::create();
    for(int i=0;i<cutAry.count;i++)
    {
        NSString *cutStr = cutAry[i];
        cutStr = [cutStr componentsSeparatedByString:@"<br>"][0];
        cutStr = [cutStr componentsSeparatedByString:@".jpg"][0];
        cutStr = [cutStr stringByAppendingString:@".jpg"];
        long long l = [cutStr length];
        if( cutStr!=nil && l>2 && l<500 && [cutStr rangeOfString:@"jpg"].location<cutStr.length+1 )
        {
//            log("     img  ----  %s", [cutStr UTF8String]);
            imgUrls->addObject( __String::createWithFormat("%s", [cutStr UTF8String]));
            imgs ++;
        }
    }
    log("\n\n");
//    if(imgUrls->count()==0)
//        log(" 解析不出图片 网页的返回内容 : \n%s", allChar);

    // 装载数据，准备回调。
    OneTaskInfo back;
    back.title = titBack;
    back.taskId = m_taskId;
    back.url = m_myURL;
    back.imgNumber = imgs;
    if(imgs>0)
        back.state = TASK_STATE_ok;
    else
        back.state = TASK_STATE_fail;
    back.ary_img = imgUrls;
    // 如果不是单个任务，就执行控制中心的回调。
    if( !m_isSingle )
        DownLoadCenter::getInstance()->oneTaskDownLoadFinish(m_taskId, m_myURL, back);
    else if( m_singleDownEndFunc )
        m_singleDownEndFunc( m_myURL );
    m_isBusying = false;
}











void HttpNode::downImage(std::string imgUrl,  OneImageDownInfo *imgInfo)
{
    if( m_isBusying ) return;
    m_isBusying = true;
    if(imgInfo){
        m_taskId = imgInfo->taskId;
        m_inTaskIdx = imgInfo->inTaskIdx;
        imgInfo->isBusying = true;
        downImgInfo = *imgInfo;
//        NSLog(@" 新接任务时，置为imgInfo != nil: 传入参数:%p - downImgInfo:%p this:%p  [taskID:%d, imgID:%d]", imgInfo,  downImgInfo ,this, m_taskId, m_inTaskIdx );
    }
    if( isImgExist( m_taskId, m_inTaskIdx) )
    {
        m_isBusying = false;
        downImgInfo.reset();
        return;
    }
    NSLog(@"新 图片下载任务: [url:%s ] == [taskId:%d index:%d ]", imgUrl.c_str(), m_taskId, m_inTaskIdx);
    // 网络异步连接方法
    HttpRequest* postRequest = new HttpRequest();
    postRequest->setRequestType( HttpRequest::Type::GET );//设置发送类型
    postRequest->setUrl( imgUrl.c_str() );//设置网址
    postRequest->setResponseCallback( [=](HttpClient* client, HttpResponse* response){
        if(downImgInfo.taskId == -1)
            NSLog(@"你麻痹 又是 nil this:%p   ", this );
        onDownLoadImageEnd(this, response);
    });
    // 传入参数
    std::string para = "";
    __String *paraStr = __String::create(para);
    postRequest->setRequestData(paraStr->getCString(),paraStr->length());
    // 下载。
    HttpClient* httpClient = HttpClient::getInstance();
    httpClient->setTimeoutForConnect(10); //设置连接超时时间</span> <span style="font-family: Arial, Helvetica, sans-serif;">
    httpClient->setTimeoutForRead(10);//设置发送超时时间
    httpClient->send(postRequest);//设置接收数据类型
    postRequest->release();//释放
}




void HttpNode::onDownLoadImageEnd(HttpNode *sender ,HttpResponse *response)
{
    if(!response) {
        log("Log:response =null,plase check it.");
    }
    else if(!response->isSucceed()){
        log("图片请求失败 onDownLoadImageEnd ERROR:%s [%s]", response->getErrorBuffer(), response->getHttpRequest()->getUrl());
        if( downImgInfo.taskId!=-1 && m_isSingle==false)
            DownLoadCenter::getInstance()->oneImageDownLoadFail(m_taskId,  &downImgInfo);
    }
    else{
        //请求成功
        std::vector<char>* buffer=response->getResponseData();
        std::string temp( buffer->begin(),buffer->end() );
        //
        std::string path = PATH_IMAGE_ALL + __String::createWithFormat("%d/", m_taskId)->getCString();
        if( FileUtils::getInstance()->isDirectoryExist(path)==false )
            FileUtils::getInstance()->createDirectory(path);
        std::string file = path + __String::createWithFormat("%d", m_inTaskIdx )->getCString();
        //保存到本地文件
        FILE *fp = fopen(file.c_str(), "wb+");
        fwrite(temp.c_str(), 1,buffer->size(), fp);
        fclose(fp);
        // log("下载图片完成: url = %s || size=%lld ", downImgInfo->imgURL.c_str(), buffer->size() );
        if( m_isSingle )
        {
            if( m_singleDownEndFunc )
                m_singleDownEndFunc( m_myURL );
        }
        else if( downImgInfo.taskId!=-1 )
            DownLoadCenter::getInstance()->oneImageDownLoadFail(m_taskId,  &downImgInfo);
        NSLog(@"下载完成后置为 nil %p -- self:%p  [地址: %s ]", &downImgInfo ,this, response->getHttpRequest()->getUrl() );
    }
    downImgInfo.reset();
    m_isBusying = false;
}










